/*
 * @Author: luthor luthor-li@qq.com
 * @Date: 2024-03-05 20:51:44
 * @LastEditors: fisher luthor-li@qq.com
 * @LastEditTime: 2024-06-19 20:29:39
 * @FilePath: \fpstream\utils\ueMsg.js
 * @Description: 基于ueMsg文件内容，按照跟叶保忠对接内容，对接口信息做调整,后续ue框架修改完成后，应当启用该文件，替换原始的ueMsg文件。
 */
import { uuid } from "./common.js";
import pako from "pako";
import str2gbk from "str2gbk";
export const useUemsg = (stream) => {
  const ueCbMap = new Map();
  const ueListenMap = new Map();
  const timeoutTimer = setInterval(() => {
    const currentTime = Date.now();
    // 遍历ueCbMap是否存在超时响应，超时即删除
    ueCbMap.forEach((val, key) => {
      if (currentTime - val.timeStamp > val.time_out) {
        ueCbMap.delete(key);
      }
    });
  }, 1000);
  const gzip = (str) => {
    return btoa(
      String.fromCharCode(...new Uint8Array(pako.gzip(str2gbk(str))))
    );
  };
  //   处理ue监听通知
  const ueNotify = (Notify) => {
    // console.log("Notify", Notify);
    const JsonRes = JSON.parse(Notify);
    const { cmd, msg_id, data, type, status_code, status_msg } = JsonRes;
    if (type == "response") {
      // 此时为响应消息使用msg_id取回调
      const target = ueCbMap.get(msg_id);
      if (target) {
        target.cb({
          msg_id: msg_id,
          data: data,
          status_code: status_code,
          status_msg: status_msg,
          type: type,
        });
        ueCbMap.delete(msg_id);
      }
      return;
    } else if (type == "push") {
      // 此时为监听消息回调
      const target = ueListenMap.get(cmd);
      if (target) {
        target({
          data: data,
          type: type,
        });
        // ueListenMap.delete(cmd);
      }
      return;
    }
  };
  stream.addResponseEventListener("handle_responses", ueNotify);
  //   发送数据到ue
  const send2Ue = (cmd, data, cb, time_out = 5000) => {
    const msg_id = uuid(16, 16);
    stream.emitUIInteraction({
      msg_id: msg_id,
      cmd: cmd,
      data: gzip(JSON.stringify(data)),
      compress: "gzip",
      time_out: time_out,
    });
    // 处理回调,将msg_id会话id作为键，注册回调函数
    if (cb)
      ueCbMap.set(msg_id, {
        cb,
        time_out: time_out,
        timeStamp: Date.now(),
      });
  };
  //   设置监听ue信息回调函数
  const listen2Ue = (cmd, cb) => {
    if (cb) ueListenMap.set(cmd, cb);
  };

  const clearMsgCb = () => {
    ueCbMap.clear();
    ueListenMap.clear();
  };

  const removeUeListener = (cmd) => {
    if (ueListenMap.get(cmd)) {
      ueListenMap.delete(cmd);
    }
  };

  return {
    send2Ue,
    listen2Ue,
    clearMsgCb,
    timeoutTimer,
    removeUeListener,
  };
};
